package lookas.csvparser.converters;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.commons.beanutils.Converter;

public class DateConverter implements Converter{

    public Calendar match(String s){
        SimpleDateFormat dateFormat = new SimpleDateFormat(
            "\"yyyy-MM-dd hh:mm:ss.SSS\"");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat(
            "\"yyyy-MM-dd hh:mm:ss.\"");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar date = Calendar.getInstance();
        try{

            date.setTime(dateFormat.parse(s));
        }catch(ParseException e1){
            try{
                date.setTime(dateFormat1.parse(s));
            }catch(ParseException e2){
                try{
                    date.setTime(dateFormat2.parse(s));
                }catch(ParseException e3){
                    try{
                        date.setTime(dateFormat3.parse(s));
                    }catch(ParseException e4){
                        date = null;
                    }
                }
            }
        }
        return date;
    }

    @SuppressWarnings("unchecked")
    public Object convert(Class type, Object value){
        Calendar date = Calendar.getInstance();
        if(type.isInstance(date)){
            return match((String)value);
        }else
            return null;
    }
}
